<template>
  <div class="app-container">
    <!-- 搜索区域 -->
    <el-card class="box-card" shadow="never">
      <i class="el-icon-search" style="font-size: 18px; margin-right: 6px"></i>
      <span>筛选搜索</span>
      <el-button
        class="btn-clear"
        size="mini"
        style="float: right; margin-left: 10px"
        @click="qingkong"
        >清空</el-button
      >
      <el-button
        type="primary"
        class="btn-find"
        size="mini"
        style="float: right"
        @click="chaxun"
        >查询</el-button
      >
      <div style="margin-top: 30px">
        <el-form
          :model="listQuery"
          ref="productForm"
          label-width="150px"
          :inline="true"
        >
          <el-form-item label="商品货号：">
            <el-input
              v-model="listQuery.productSn"
              style="width: 150px"
            ></el-input>
          </el-form-item>
          <el-form-item label="商品所属分类：">
            <el-cascader
              v-model="productCateValue"
              :options="productCateOptions"
              :props="{ expandTrigger: 'hover' }"
              style="width: 150px"
            ></el-cascader>
          </el-form-item>
          <el-form-item label="上架状态：">
            <el-select
              v-model="listQuery.publishStatus"
              placeholder="请选择商品是否上架"
              style="width: 150px"
            >
              <el-option
                v-for="item in publishStatusOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              >
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="商品名称：">
            <el-input v-model="listQuery.name" style="width: 150px"></el-input>
          </el-form-item>
        </el-form>
      </div>
    </el-card>

    <!--表头和表格区域-->
    <div style="margin-top: 30px">
      <!--表头-->
      <el-card class="box-card" shadow="never">
        <i
          class="el-icon-s-order"
          style="font-size: 18px; margin-right: 6px"
        ></i>
        <span>商品列表</span>
        <el-button
          class="btn-add"
          size="mini"
          type="primary"
          style="float: right"
          @click="$router.push('/pm/addProduct')"
          >添加</el-button
        >
      </el-card>
      <!--表格-->
      <div class="table-container">
        <el-table
          border
          :data="dataList"
          ref="multipleTable"
          style="width: 100%"
          :height="getHeight()"
          v-loading="isLoading"
          @selection-change="handleSelect"
          @select-all="handleSelect"
        >
          <el-table-column type="selection" width="55"> </el-table-column>
          <el-table-column label="编号" align="center" width="100">
            <template slot-scope="scope">
              {{ scope.row.id }}
            </template>
          </el-table-column>
          <el-table-column label="商品图片" align="center" width="160">
            <template slot-scope="scope">
              <img
                :src="scope.row.pic"
                alt=""
                style="width: 80px; height: 80px"
              />
            </template>
          </el-table-column>
          <el-table-column label="商品名称" align="center" width="200">
            <template slot-scope="scope">
              {{ scope.row.name }}
            </template>
          </el-table-column>
          <el-table-column label="价格/货号" align="center" width="180">
            <template slot-scope="scope">
              <p>市场价：{{ scope.row.price }}</p>
              <p>货号：{{ scope.row.productSn }}</p>
            </template>
          </el-table-column>
          <el-table-column label="操作" align="center" width="180">
            <template slot-scope="scope">
              <p>
                上架：<el-switch
                  v-model="scope.row.publishStatus"
                  :active-value="1"
                  :inactive-value="0"
                  @change="shangjia(scope.$index, scope.row)"
                ></el-switch>
              </p>
              <p>
                新品：<el-switch
                  v-model="scope.row.newsStatus"
                  :active-value="0"
                  :inactive-value="1"
                  @change="xinpin(scope.$index, scope.row)"
                ></el-switch>
              </p>
              <p>
                推荐：<el-switch
                  v-model="scope.row.recommendStatus"
                  :active-value="1"
                  :inactive-value="0"
                  @change="tuijian(scope.$index, scope.row)"
                ></el-switch>
              </p>
            </template>
          </el-table-column>
          <el-table-column label="销量" align="center" width="100">
            <template slot-scope="scope">
              {{ scope.row.sale ? scope.row.sale : "暂无销量" }}
            </template>
          </el-table-column>
          <el-table-column label="存量" align="center" width="100">
            <template slot-scope="scope">
              {{ scope.row.store }}
            </template>
          </el-table-column>
          <el-table-column label="操作" align="center">
            <template slot-scope="scope">
              <el-button size="mini" @click="bianji(scope.$index, scope.row)"
                >编辑</el-button
              >
              <el-button
                size="mini"
                type="danger"
                @click="shanchu(scope.$index, scope.row)"
                >删除</el-button
              >
            </template>
          </el-table-column>
        </el-table>
      </div>
    </div>

    <!--批量操作区域-->
    <div class="many-operate-container">
      <el-select
        size="small"
        placeholder="批量操作列表"
        style="width: 150px"
        v-model="operatesType"
      >
        <el-option
          v-for="item in operates"
          :key="item.value"
          :label="item.label"
          :value="item.value"
        >
        </el-option>
      </el-select>
      <el-button
        style="margin-left: 10px"
        size="mini"
        type="danger"
        @click="piliangcaozuo"
        >确实</el-button
      >
    </div>

    <!--分页区域-->
    <div class="pagination-container">
      <el-pagination
        layout="total,sizes,prev, pager, next,jumper"
        :total="total"
        :page-size="listQuery.pageSize"
        :current-page="listQuery.pageNum"
        :page-sizes="[5, 10, 15]"
        @current-change="handlePageChange"
        @size-change="handleSizeChange"
      >
      </el-pagination>
    </div>
  </div>
</template>

<script>
import { getCategoryWithChildren } from "../../../../api/categoryApi";
import {
  getProductList,
  delOneProduct,
  updateProductWithList,
  updateProductWithListMany,
  deleteProductWithListMany,
} from "../../../../api/productApi";
let defaultQuery = {
  productSn: null, // 货号
  productCategoryId: null, // 所谓分类
  publishStatus: null, // 上架的状态
  name: null, // 商品名称
  pageNum: 1, // 当前第几页
  pageSize: 5, // 一页多少条数据
};
export default {
  name: "index",
  data() {
    return {
      operatesType: null,
      listQuery: Object.assign({}, defaultQuery),
      productCateValue: [], // 代表你选中的分类数据
      productCateOptions: [], // 分类的所有的数据
      publishStatusOptions: [
        { value: 1, label: "上架" },
        { value: 0, label: "下架" },
      ],
      dataList: [], // 表格中的数据源
      isLoading: false, // 发送ajax时的loading效果
      total: 0, // 总记录数
      operates: [
        { label: "批量上架", value: "publishOn" },
        { label: "批量下架", value: "publishOff" },
        { label: "批量推荐", value: "recommendOn" },
        { label: "批量取消推荐", value: "recommendOff" },
        { label: "批量上新", value: "newsOn" },
        { label: "批量下新", value: "newsOff" },
        { label: "批量删除", value: "manyDel" },
      ],
      multipleSelection: [], // 选中的商品的
    };
  },
  created() {
    this.getCategoryList(); // 获取所有的分类数据
    this.getList(); // 获取商品列表数据
  },
  methods: {
    //查询
    chaxun() {
      this.listQuery.pageNum = 1;
      this.getList();
    },
    //清空
    qingkong() {
      this.listQuery = Object.assign({}, defaultQuery);
      this.productCateValue = [];
      this.getList();
    },
    //编辑
    bianji(index, row) {
      this.$router.push({
        path: "/pm/addProduct",
        query: { id: row.id },
      });
    },
    //删除
    shanchu(index, row) {
      console.log(row);
      this.$confirm("此操作将永久删除该文件, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          delOneProduct(row.id).then((res) => {
            if (res.status === 1) {
              this.$message({
                type: "success",
                message: "删除成功!",
              });
            } else {
              this.$message.error("删除失败");
            }
            this.getList(); // 删除完后，需要重新获取数据源
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    //是否 上架 新品 推荐 整体封装一个方法
    localUpdateProduct(paramsObj) {
      updateProductWithList(paramsObj).then((res) => {
        if (res.status == 1) {
          this.$message.success(res.msg);
        } else {
          this.$message.error(res.msg);
        }
      });
    },
    //是否上架
    shangjia(index, row) {
      this.localUpdateProduct({ id: row.id, publishStatus: row.publishStatus });
    },
    //是否新品
    xinpin(index, row) {
      this.localUpdateProduct({ id: row.id, newsStatus: row.newsStatus });
    },
    //是否推荐
    tuijian(index, row) {
      this.localUpdateProduct({
        id: row.id,
        recommendStatus: row.recommendStatus,
      });
    },
    //获取一级二级分类表单
    getCategoryList() {
      getCategoryWithChildren().then((res) => {
        console.log(res);
        if (res.status == 1) {
          let datadata = res.data;
          this.productCateOptions = [];
          for (let i = 0; i < datadata.length; i++) {
            let children = [];
            if (datadata[i].children !== null) {
              for (let j = 0; j < datadata[i].children.length; j++) {
                children.push({
                  value: datadata[i].children[j].id,
                  label: datadata[i].children[j].name,
                });
              }
            }
            children = children.length > 0 ? children : null;
            this.productCateOptions.push({
              value: datadata[i].id,
              label: datadata[i].name,
              children: children,
            });
          }
        }
      });
    },
    //获取表格数据
    getList() {
      getProductList(this.listQuery).then((res) => {
        console.log(res);
        if (res.status == 1) {
          this.$message.success(res.msg);
          this.isLoading = false;
          this.dataList = res.data.product_list;
          this.total = res.data.product_count;
        }
      });
    },
    // 计算表格的高度
    getHeight() {
      return window.innerHeight - 250;
    },
    // 合选 和 选中某一个用户
    handleSelect(select) {
      this.multipleSelection = select;
    },
    // 点击页码
    handlePageChange(val) {
      this.listQuery.pageNum = val;
      this.getList();
    },
    // 点击一页显示多少条
    handleSizeChange(val) {
      this.listQuery.pageSize = val;
      this.listQuery.pageNum = 1;
      this.getList();
    },
    //批量操作
    piliangcaozuo() {
      console.log(this.multipleSelection);
      if (
        this.multipleSelection == null ||
        this.multipleSelection == undefined ||
        this.multipleSelection == ""
      ) {
        return this.$message.warning("请选择你要操作的商品");
      }
      if (
        this.operatesType == null ||
        this.operatesType == undefined ||
        this.operatesType == ""
      ) {
        return this.$message.warning("请选择你要操作的选项");
      }
      this.$confirm("此操作将进行批量操作, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          let ids = [];
          for (let i = 0; i < this.multipleSelection.length; i++) {
            ids.push(this.multipleSelection[i].id);
          }
          switch (this.operatesType) {
            case this.operates[0].value:
              this.piliangshangjia(1, ids);
              break;
            case this.operates[1].value:
              this.piliangshangjia(0, ids);
              break;
            case this.operates[2].value:
              this.piliangtuijian(1, ids);
              break;
            case this.operates[3].value:
              this.piliangtuijian(0, ids);
              break;
            case this.operates[4].value:
              this.piliangshangxin(0, ids);
              break;
            case this.operates[5].value:
              this.piliangshangxin(1, ids);
              break;
            case this.operates[6].value:
              this.piliangshanchu(ids);
              break;
          }
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消批量操作",
          });
        });
    },
    //批量上架 下架
    piliangshangjia(status, ids) {
      updateProductWithListMany({ ids: ids, publishStatus: status }).then(
        (res) => {
          console.log("res",res);
          if (res.status == 1) {
            this.$message.success("批量操作成功");
          } else {
            this.$message.error("批量操作失败");
          }
          this.getList();
        }
      );
    },
    //批量推荐 取消推荐
    piliangtuijian(status, ids) {
      updateProductWithListMany({ ids: ids, recommendStatus: status }).then(
        (res) => {
          if (res.status == 1) {
            this.$message.success("批量操作成功");
          } else {
            this.$message.error("批量操作失败");
          }
          this.getList();
        }
      );
    },
    //批量上新 下新
    piliangshangxin(status, ids) {
      updateProductWithListMany({ ids: ids, newsStatus: status }).then((res) => {
        if (res.status == 1) {
          this.$message.success("批量操作成功");
        } else {
          this.$message.error("批量操作失败");
        }
        this.getList();
      });
    },
    //批量删除
    piliangshanchu(ids) {
      deleteProductWithListMany({ids:ids}).then((res) => {
        if (res.status == 1) {
          this.$message.success("批量删除成功");
        } else {
          this.$message.error("批量删除失败");
        }
        this.getList();
      });
    },
  },
};
</script>

<style scoped>
</style>